package first.endtoend

import com.google.android.gcm.server.Message
import com.google.android.gcm.server.MulticastResult
import com.google.android.gcm.server.Result
import com.google.android.gcm.server.Sender
import first.endtoend.Agent

class SendNotificationService
{
    def familyService

    private String apiKey = "AIzaSyAVa-etOl80q8rsLKy7ChVVOO6bg9mjm08"

    /*
     sendNotification : method to send a notification
     to some concerned devices to update/reload Agent' local DB
     */

    def void sendNotification(Agent anAgent, String aMessage)
    {


        String regId = anAgent.regId
        println("here regId iiis" + regId)
        if (anAgent.regId != null)
        {

            Sender sender = new Sender(apiKey);
            Message message = new Message.Builder()
                    .addData("message",
                    aMessage)
                    .build();
            Result result = null;


            try
            {
                result = sender.send(message, regId, 1);
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            System.out.println(result.toString());
        } else
        {
            //regId null
        }
    }

    /*
    sendNotificationToAll : method to send a notification
    to some concerned devices to update/reload Agent' local DB
    */

    def sendNotificationToAll(List<Agent> agentList, String aMessqge)
    {

        List<String> deviceList = new ArrayList<String>()
        agentList.each {
            deviceList.add(it.regId)
        }

        if (deviceList.size() != 0)
        {

            Sender sender = new Sender(apiKey);
            Message message = new Message.Builder()
                    .addData("message",
                    aMessqge)
                    .build();
            MulticastResult result = null;


            try
            {
                result = sender.send(message, deviceList, 1);
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            System.out.println(result.toString());

        } else
        {
            //there is no list
        }

    }

}
